using LocalPort_Listener.Models;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;

namespace LocalPort_Listener
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        BaseLibrary.ClassLibrary.CTimer timer_Listen=new BaseLibrary.ClassLibrary.CTimer() {  Interval=5000};
        BaseLibrary.ClassLibrary.CTimer timer_UI = new BaseLibrary.ClassLibrary.CTimer() { Interval = 5000 };
        Dictionary<int, BaseLibrary.ClassLibrary.EAFLog.Log> log_dic = new Dictionary<int, BaseLibrary.ClassLibrary.EAFLog.Log>();
        List<PortInfo> ports = new List<PortInfo>();


        int[] listen_Ports = new int[0];
        private void Form1_Load(object sender, EventArgs e)
        {
            string hostName = Dns.GetHostName();
            List<string> addresses = Dns.GetHostAddresses(hostName).Select(c=>c.ToString()).ToList();
            addresses.Add("127.0.0.1");
            addresses.Add("local");
            addresses.Add("localhost");
            timer_UI.Start(() => {
                BaseLibrary.ClassLibrary.Win32.WinForm.Invoke(() => {
                    var v = textBox_Ports.Text.Trim().Split(',').Select(c => BaseLibrary.ClassLibrary.DataConver.ToInt(c)).Where(c => c > 0).ToArray();
                    lock (listen_Ports)
                        listen_Ports = v;
                    portInfoBindingSource.DataSource = ports.OrderBy(c => c.Port).ToArray();
                    dataGridView1.Refresh();
                });
            });
            timer_Listen.Start(() =>
            {
                var tcpProgressInfoTable = TcpConnectionTableHelper.GetAllTcpConnections();
                if (tcpProgressInfoTable != null && tcpProgressInfoTable.Length > 0)
                {
                    lock (ports)
                    {
                        ports.Clear();
                        foreach (var v in tcpProgressInfoTable.Where(c => listen_Ports.Contains(c.LocalPort) && addresses.Contains((TcpConnectionTableHelper.GetIpAddress(c.remoteAddr))) && c.RemotePort>0))
                        {
                            PortInfo tem ;
                            ports.Add(tem=new PortInfo()
                            {
                                Port = v.LocalPort,
                                ProcessID = v.owningPid,
                                RemoteIP = TcpConnectionTableHelper.GetIpAddress(v.remoteAddr),
                                RemotePort = v.RemotePort,
                                RemoteProcessID = tcpProgressInfoTable.FirstOrDefault(c => c.LocalPort == v.RemotePort).owningPid
                            });
                            {
                                try
                                {
                                    Process process = Process.GetProcessById(tem.ProcessID);
                                    if (process != null)
                                    {
                                        tem.ProcessName = process.ProcessName;
                                    }
                                }
                                catch { }
                                try
                                {
                                    Process process = Process.GetProcessById(tem.RemoteProcessID);
                                    if (process != null)
                                    {
                                        tem.RemoteProcessName = process.ProcessName;
                                        tem.RemoteProcessFilePath = process.MainModule?.FileName;
                                    }
                                }
                                catch
                                {

                                }
                            }
                            var log = log_dic.ContainsKey(v.LocalPort) ? log_dic[v.LocalPort] : null;
                            if (log == null)
                                log_dic.Add(v.LocalPort, log = new BaseLibrary.ClassLibrary.EAFLog.Log() { path = Path.Combine(Application.StartupPath, "log", v.LocalPort.ToString()), SaveDay = 2 });
                            log.Write(Newtonsoft.Json.JsonConvert.SerializeObject(tem));
                        }
                    }
                }
            });
        }
     
    }
}
